//
//  CHSSortTimeAndDistance.m
//  ZXCategories_Example
//
//  Created by zhuxm2023 on 2024/8/1.
//  Copyright © 2024 海参. All rights reserved.
//

#import "CHSSortTimeAndDistance.h"


@interface MyClass : NSObject
@property (nonatomic, strong) NSDate *time;
@property (nonatomic, assign) NSInteger distance;
@end

@implementation MyClass
@end



@implementation CHSSortTimeAndDistance


- (void)sortTimeAndDistance{
    
    MyClass *obj1 = [[MyClass alloc] init];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat: @"yyyy-MM-dd"];
    NSDate *date1 = [formatter1 dateFromString:@"2022-01-04"];
    obj1.time = date1;
    obj1.distance = 500;

    MyClass *obj2 = [[MyClass alloc] init];
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
    [formatter2 setDateFormat: @"yyyy-MM-dd"];
    NSDate *date2 = [formatter2 dateFromString:@"2022-01-04"];
    obj2.time = date2;
    obj2.distance = 300;

    MyClass *obj3 = [[MyClass alloc] init];
    NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init];
    [formatter3 setDateFormat: @"yyyy-MM-dd"];
    NSDate *date3 = [formatter3 dateFromString:@"2022-01-03"];
    obj3.time = date3;
    obj3.distance = 400;

    MyClass *obj4 = [[MyClass alloc] init];
    NSDateFormatter *formatter4 = [[NSDateFormatter alloc] init];
    [formatter4 setDateFormat: @"yyyy-MM-dd"];
    NSDate *date4 = [formatter4 dateFromString:@"2022-01-02"];
    obj4.time = date4;
    obj4.distance = 600;

    NSArray *data = @[obj1, obj2, obj3, obj4];
    
    NSArray *sortedData = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
             MyClass *myObj1 = (MyClass *)obj1;
             MyClass *myObj2 = (MyClass *)obj2;
             NSComparisonResult result = [myObj1.time compare:myObj2.time];
             if (result == NSOrderedSame) {
                 result = [[NSNumber numberWithInteger:myObj1.distance] compare:[NSNumber numberWithInteger:myObj2.distance]];
             }
             else if (result == NSOrderedAscending) {
                 result = NSOrderedDescending;
             }
             else if (result == NSOrderedDescending) {
                 result = NSOrderedAscending;
             }
             return result;
         }];

    for (MyClass *obj in sortedData) {
        NSLog(@"%@ %ld", obj.time, (long)obj.distance);
    }
    
}


@end
